<template>
  <BottomDrawer
    :visible="addVisible"
    :title="'患者信息'"
    :width="1000"
    @close="addVisible = false"
  >
    <div class="form-container">
      <form>
        <div class="form-row">
          <div class="form-item">
            <label for="name"><span class="required">*</span>姓名</label>
            <input type="text" id="name" v-model="formData.patientName" />
          </div>
          <div class="form-item">
            <label for="gender"><span class="required">*</span>性别</label>
            <div class="gender-select-container">
              <div
                class="gender-option"
                :class="{ active: patientGender === '男' }"
                @click="onPatientSex('男')"
              >
                男
              </div>
              <div
                class="gender-option"
                :class="{ active: patientGender === '女' }"
                @click="onPatientSex('女')"
              >
                女
              </div>
            </div>
          </div>
          <div class="form-item">
            <label for="phone"><span class="required">*</span>电话</label>
            <input type="text" id="phone" v-model="formData.patientPhone" />
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label for="idNumber">身份证号</label>
            <input type="text" id="idNumber" v-model="formData.idCard" />
          </div>
          <div class="form-item">
            <label for="solarBirthday">阳历生日</label>
            <el-date-picker
              type="date"
              v-model="formData.solarBirthday"
              placeholder="选择阳历生日"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
            <div class="input__prefix">
              <img src="@/assets/icon/calendar.svg" alt="" />
            </div>
          </div>
          <div class="form-item">
            <label for="lunarBirthday">阴历生日</label>
            <el-date-picker
              type="date"
              placeholder="选择阴历生日"
              format="YYYY-MM-DD"
              v-model="formData.lunarBirthday"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            >
            </el-date-picker>
            <div class="input__prefix">
              <img src="@/assets/icon/calendar.svg" alt="" />
            </div>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label for="height">身高</label>
            <el-input type="text" v-model="formData.height">
              <template #suffix> cm </template>
            </el-input>
          </div>
          <div class="form-item">
            <label for="weight">体重</label>
            <el-input type="text" v-model="formData.weight">
              <template #suffix> kg </template>
            </el-input>
          </div>
          <div class="form-item">
            <label for="bloodPressure">血压</label>
            <div class="blood-pressure-input-container">
              <input
                type="text"
                class="pressure-input"
                v-model="formData.systolicBp"
                placeholder="收缩压"
              />
              <span class="separator">/</span>
              <input
                type="text"
                class="pressure-input"
                v-model="formData.diastolicBp"
                placeholder="舒张压"
              />
              <span class="unit">mmHg</span>
            </div>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label for="ethnicity">民族</label>
            <!-- <input type="text" id="ethnicity" /> -->
            <el-select
              placeholder=""
              style="width: 293px"
              v-model="formData.ethnicity"
            >
              <el-option
                v-for="item in ethnicityEnum"
                :key="item.text"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="form-item">
            <label for="gender"><span class="required">*</span>是否已婚</label>
            <div class="gender-select-container">
              <div
                class="gender-option"
                :class="{ active: marriage === '已婚' }"
                @click="onMarriage('已婚')"
              >
                已婚
              </div>
              <div
                class="gender-option"
                :class="{ active: marriage === '未婚' }"
                @click="onMarriage('未婚')"
              >
                未婚
              </div>
            </div>
          </div>
          <div class="form-item">
            <label for="bloodPressure">年龄</label>
            <div class="blood-pressure-input-container">
              <input
                type="text"
                class="pressure-input"
                v-model="formData.ageYear"
              />
              <span class="separator">岁</span>
              <input
                type="text"
                class="pressure-input"
                v-model="formData.ageMonth"
              />
              <span class="unit">月</span>
            </div>
          </div>
        </div>
        <div class="form-row">
          <div class="form-item">
            <label for="unit">单位</label>
            <input type="text" id="unit" v-model="formData.company" />
          </div>
          <div class="form-item">
            <label for="occupation">职业</label>
            <input type="text" id="occupation" v-model="formData.job" />
          </div>
        </div>
        <div class="form-item full-width">
          <label for="addressList">家庭住址</label>
          <!-- <input type="text" id="address" v-model="formData.address" /> -->
          <el-cascader
            v-model="formData.addressList"
            :options="getCascaderOptions()"
            :props="{
              value: 'code',
              label: 'name',
              children: 'children',
            }"
            :style="{
              width: '100%',
            }"
            :placeholder="'请选择省市县'"
            @change="(value) => handleRegionChange(value)"
            clearable
            filterable
          />
        </div>
        <div class="form-item full-width">
          <label for="addressList">详细地址</label>
          <input type="text" id="address" v-model="formData.address" />
        </div>
        <div class="form-item full-width">
          <label for="remarks">备注</label>
          <input type="text" id="remarks" v-model="formData.remark" />
        </div>

        <div class="history-form">
          <div class="table-container">
            <div class="table-row">
              <div class="table-cell label-cell">
                <span>既往史</span>
              </div>
              <div class="table-cell input-cell">
                <input
                  type="text"
                  id="medicalHistory"
                  @focus="onBlur"
                  v-model="formData.medicalHistory"
                />
                <div
                  class="patient-popup"
                  ref="medicalHistoryPopupRef"
                  style="position: absolute; bottom: 86px"
                  v-if="isPatient"
                >
                  <SymptomList
                    @onClose="onClose"
                    :symptomList="medicalList"
                    v-if="medicalResponse[0]?.fieldStyle == '2'"
                    :content="formData.medicalHistory"
                     @onCloseDel="onCloseDel"
                  ></SymptomList>

                  <Medical
                    :medicalList="medicalList"
                    @on-close="onClose"
                    :content="formData.medicalHistory"
                     @onCloseDel="onCloseDel"
                    v-if="medicalResponse[0]?.fieldStyle == '3'"
                  ></Medical>
                </div>
              </div>
            </div>
            <div class="table-row">
              <div class="table-cell label-cell">过敏史</div>
              <div class="table-cell input-cell">
                <input
                  type="text"
                  id="allergyHistory"
                  @focus="onBlur_1"
                  v-model="formData.allergyHistory"
                />
                <div
                  class="patient-popup"
                  ref="allergyHistoryPopupRef"
                  style="position: absolute; bottom: 86px"
                  v-if="isPatient1"
                >
                  <!-- <Medical
                    :medicalList="medicalList"
                    @on-close="onClose"
                    @onSymptom="onSymptom"
                  ></Medical> -->
                  <SymptomList
                    @onClose="onClose"
                    :content="formData.allergyHistory"
                    :symptomList="medicalList"
                    v-if="medicalResponse[1]?.fieldStyle == '2'"
                    @onSymptom="onSymptom1"
                  ></SymptomList>

                  <Medical
                    :medicalList="medicalList"
                    @on-close="onClose"
                    :content="formData.allergyHistory"
                    @onSymptom="onSymptom1"
                    v-if="medicalResponse[1]?.fieldStyle == '3'"
                  ></Medical>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
      <el-button
        style="float: right; margin-top: 20px"
        type="primary"
        @click="onAddPatient"
        >保存</el-button
      >
    </div>
  </BottomDrawer>
</template>

<script setup lang="ts">
import type {
  FormRules,
  FormInstance,
  ElUpload,
  CascaderValue,
} from 'element-plus';
import { ref, shallowRef, reactive, onMounted, onUnmounted } from 'vue';
import { Calendar } from '@element-plus/icons-vue';
import {
  addPatient,
  getPatientMedicalField,
  updatePatient,
} from '@/api/patient';
import store from '@/store';
interface MedicalField {
  treeList?: any[];
  [key: string]: any;
}
const medicalList = ref<any[]>([]);
const medicalResponse = ref<MedicalField[]>([]);
const props = defineProps<{
  addType: string; // '1'表示添加新患者，'2'表示编辑患者;
}>();
// 这里可以添加组件的逻辑代码，例如数据绑定、事件处理等
const emits = defineEmits<{
  (e: 'refresh'): void;
}>();
defineExpose<{
  open: () => void;
  open1: (row: any) => void;
}>({
  open: async () => {
    addVisible.value = true;
    formData.value = {
      patientName: '', //患者名
      patientGender: '1', //患者性别;1男生2女生3未知SexEnum
      patientPhone: '', //患者电话
      idCard: '', //身份证号
      ageYear: null, //年龄年;5代表5岁
      ageMonth: null, //年龄月;2代表2个月
      lunarBirthday: '', //阴历生日
      solarBirthday: '', //阳历生日
      weight: null, //体重;53.8kg
      systolicBp: null, //收缩压;120mmHg
      diastolicBp: null, //舒张压;80mmHg
      height: null, //身高;183cm
      ethnicity: '1', //民族EthnicityEnum
      isMarried: '1', //婚否;1是0否YesOrNoEnum
      company: '', //单位
      job: '', //职业
      province: '', //省份
      city: '', //市区
      county: '', //县
      address: '', //家庭住址
      addressList: [], //家庭住址
      medicalHistory: '', //既往史
      allergyHistory: '', //过敏史
      remark: '', //备注
      lastRechargeTime: '', // 新增属性，最后充值时间
      fieldList: [], // 新增属性，字段列表
    };
    const refult = await getPatientMedicalField();
    if (refult && refult.data) {
      medicalResponse.value = refult.data;
    }
  },
  open1: async (row: any) => {
    formData.value = JSON.parse(JSON.stringify(row));

    formData.value.addressList = [
      Number(row.province),
      Number(row.city),
      Number(row.county),
    ];
    patientGender.value =
      row.patientGender === '1'
        ? '男'
        : row.patientGender === '2'
        ? '女'
        : '未知';
    addVisible.value = true;
    const refult = await getPatientMedicalField();
    if (refult && refult.data) {
      medicalResponse.value = refult.data;
    }
  },
});
const userEnums = store.useBaseDataStore();
const ethnicityEnum = userEnums.getEnumSelect('ethnicityEnum');
const getCascaderOptions = () => {
  return userEnums.regions;
};
// 使用 shallowRef 或 markRaw 处理组件
const calendarIcon = shallowRef(Calendar);
const addVisible = ref(false);
const selectedGender = ref('男');
const formData = ref<any>({
  patientName: '', //患者名
  patientGender: '', //患者性别;1男生2女生3未知SexEnum
  patientPhone: '', //患者电话
  idCard: '', //身份证号
  ageYear: null, //年龄年;5代表5岁
  ageMonth: null, //年龄月;2代表2个月
  lunarBirthday: '', //阴历生日
  solarBirthday: '', //阳历生日
  weight: null, //体重;53.8kg
  systolicBp: null, //收缩压;120mmHg
  diastolicBp: null, //舒张压;80mmHg
  height: null, //身高;183cm
  ethnicity: '1', //民族EthnicityEnum
  isMarried: '1', //婚否;1是0否YesOrNoEnum
  company: '', //单位
  job: '', //职业
  province: '', //省份
  city: '', //市区
  county: '', //县
  addressList: [], //家庭住址
  medicalHistory: '', //既往史
  allergyHistory: '', //过敏史
  remark: '', //备注
  address: '', //家庭住址
  lastRechargeTime: '', // 新增属性，最后充值时间
  fieldList: [], // 新增属性，字段列表
});
const marriage = ref('已婚');
const patientGender = ref('男');
const solarBirthday = ref('');
const lunarBirthday = ref('');
const isPatient = ref(false);
const isPatient1 = ref(false);
// 弹层容器引用
const medicalHistoryPopupRef = ref<HTMLElement | null>(null);
const allergyHistoryPopupRef = ref<HTMLElement | null>(null);
const ethnicityList = ref([
  { label: '汉族', value: '汉族' },
  { label: '满族', value: '满族' },
  { label: '回族', value: '回族' },
  { label: '藏族', value: '藏族' },
  { label: '维吾尔族', value: '维吾尔族' },
  { label: '苗族', value: '苗族' },
  { label: '彝族', value: '彝族' },
  { label: '壮族', value: '壮族' },
]);
const onMarriage = (value: string) => {
  marriage.value = value;
  formData.value.isMarried = value === '已婚' ? '1' : '0';
};
const selectGender = (gender: string) => {
  selectedGender.value = gender;
};
const onPatientSex = (value: string) => {
  if (value == '男') {
    formData.value.patientGender = '1';
  } else {
    formData.value.patientGender = '2';
  }
  patientGender.value = value;
};
// 病史
const onBlur = () => {
  // 这里可以添加失去焦点时的逻辑
  //console.log('输入框失去焦点');
  isPatient.value = true; // 打开既往史
  isPatient1.value = false; // 关闭过敏史
  medicalList.value = medicalResponse.value[0]?.treeList ?? [];
};
const onBlur_1 = () => {
  // 这里可以添加失去焦点时的逻辑
  //console.log('输入框失去焦点');
  isPatient1.value = true; // 打开过敏史
  isPatient.value = false; // 关闭既往史
  medicalList.value = medicalResponse.value[1]?.treeList ?? [];
};
// 处理区域变化
const handleRegionChange = (value: CascaderValue | null | undefined) => {
  formData.value.addressList = value;
};
const onClose = () => {
  isPatient.value = false; // 关闭病史弹窗
  isPatient1.value = false;
  medicalList.value = []; // 清空病史列表
};
const onCloseDel = () => {
  formData.value.medicalHistory =  formData.value.medicalHistory.slice(0, -1);
};
const onSymptom = (symptom: any) => {
  // 这里可以添加选中症状的逻辑，例如将选中的症状传递给父组件
  //console.log('选中的症状:', symptom);
  // 统一整理本次传入的症状列表
  // 统一整理本次传入的症状列表
  //   let incoming: string[] = [];
  //   if (Array.isArray(symptom)) {
  //     incoming = symptom
  //       .map((s: any) => (s?.text ?? s)?.toString().trim())
  //       .filter(Boolean);
  //   } else {
  //     incoming = [(symptom?.text ?? symptom)?.toString().trim()].filter(
  //       Boolean
  //     );
  //   }
  //   const sep = '，';
  // formData.value.medicalHistory += incoming.join(sep);// 将选中的症状添加到既往史中

  const prevRaw = (formData.value.medicalHistory ?? '').toString().trim();
  const existingSet = new Set(
    prevRaw
      ? prevRaw
          .split(/[，,]+/)
          .map((s: string) => s.trim())
          .filter(Boolean)
      : []
  );

  // // 统一整理本次传入的症状列表
  // let incoming: string[] = [];
  // if (Array.isArray(symptom)) {
  //   incoming = symptom
  //     .map((s: any) => (s?.text ?? s)?.toString().trim())
  //     .filter(Boolean);
  // } else {
  //   incoming = [(symptom?.text ?? symptom)?.toString().trim()].filter(Boolean);
  // }

  // // 过滤掉已经存在的，避免重复
  // const newItems = incoming.filter((it) => !existingSet.has(it));
  // if (newItems.length === 0) return; // 没有新增内容则不更新

  // const sep = '，';
  // const prefix = prevRaw
  //   ? /[，,]$/.test(prevRaw)
  //     ? prevRaw
  //     : prevRaw + sep
  //   : '';
  // const appended = prefix + newItems.join(sep);
  let data = '';
  symptom.forEach((item: { type: any; text: any }) => {
    if (item.type) {
      data += `${item.text}`;
    } else {
      data += `，${item.text}`;
    }
  });
  formData.value.medicalHistory += data;
};
const onSymptom1 = (symptom: any) => {
  // 这里可以添加选中症状的逻辑，例如将选中的症状传递给父组件
  //console.log('选中的症状:', symptom);
  // formData.value.allergyHistory += symptom + ';'; // 将选中的症状添加到既往史中

  const prevRaw = (formData.value.allergyHistory ?? '').toString().trim();
  const existingSet = new Set(
    prevRaw
      ? prevRaw
          .split(/[，,]+/)
          .map((s: string) => s.trim())
          .filter(Boolean)
      : []
  );

  // 统一整理本次传入的症状列表
  let incoming: string[] = [];
  if (Array.isArray(symptom)) {
    incoming = symptom
      .map((s: any) => (s?.text ?? s)?.toString().trim())
      .filter(Boolean);
  } else {
    incoming = [(symptom?.text ?? symptom)?.toString().trim()].filter(Boolean);
  }

  // 过滤掉已经存在的，避免重复
  const newItems = incoming.filter((it) => !existingSet.has(it));
  if (newItems.length === 0) return; // 没有新增内容则不更新

  const sep = '，';
  const prefix = prevRaw
    ? /[，,]$/.test(prevRaw)
      ? prevRaw
      : prevRaw + sep
    : '';
  const appended = prefix + newItems.join(sep);
  formData.value.allergyHistory = appended;
};
const onAddPatient = async () => {
  // 这里可以添加保存患者信息的逻辑
  //console.log(formData.value.addressList);
  const addressArr = formData.value.addressList as string[];
  formData.value.province = addressArr[0] || '';
  formData.value.city = addressArr[1] || '';
  formData.value.county = addressArr[2] || '';
  // formData.value.addressList = [];
  if (props.addType === '1') {
    const data = await addPatient(formData.value);
    if (data.code == '200') {
      //console.log('患者信息保存成功:', data);
      ElMessage({
        type: 'success',
        message: '患者信息保存成功',
      });
      addVisible.value = false; // 关闭弹窗
      emits('refresh');
    } else {
    }
  } else if (props.addType === '2') {
    const data = await updatePatient(formData.value);
    if (data.code == '200') {
      //console.log('患者信息编辑成功:', data);
      ElMessage({
        type: 'success',
        message: '患者信息编辑成功',
      });
      addVisible.value = false; // 关闭弹窗
      emits('refresh');
    } else {
    }
  }
};

// 点击其它位置关闭弹层（不包含自身与触发输入）
const handleGlobalClick = (e: MouseEvent) => {
  const target = e.target as HTMLElement;
  const path: HTMLElement[] = (e as any).composedPath?.() || [];
  const inMedical =
    !!medicalHistoryPopupRef.value &&
    (medicalHistoryPopupRef.value.contains(target) ||
      path.includes(medicalHistoryPopupRef.value));
  const inAllergy =
    !!allergyHistoryPopupRef.value &&
    (allergyHistoryPopupRef.value.contains(target) ||
      path.includes(allergyHistoryPopupRef.value));
  const isTriggerMedical = target.id === 'medicalHistory';
  const isTriggerAllergy = target.id === 'allergyHistory';

  if (isPatient.value && !inMedical && !isTriggerMedical) {
    isPatient.value = false;
  }
  if (isPatient1.value && !inAllergy && !isTriggerAllergy) {
    isPatient1.value = false;
  }
};

onMounted(() => {
  document.addEventListener('click', handleGlobalClick, true); // 捕获阶段更早拦截
});
onUnmounted(() => {
  document.removeEventListener('click', handleGlobalClick, true);
});
</script>

<style scoped lang="scss">
/* 去除 contenteditable 选中时的黑色边框 */
[contenteditable='true']:focus {
  outline: none;
  box-shadow: none;
}

.form-container {
  padding: 20px;
  border-radius: 5px;
}

.form-row {
  display: flex;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
  margin-right: 15px;
  position: relative;
}

.form-item:last-child {
  margin-right: 0;
}

.full-width {
  width: 100%;
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  color: #666;
}

.required {
  color: red;
}

input {
  width: 100%;
  padding: 8px;
  border: 1px solid #dcdfe6; // 统一与 Element Plus 默认边框色
  border-radius: 3px;
  background: #fff;
  transition: border-color 0.15s ease, box-shadow 0.15s ease;
  outline: none;
  box-shadow: none;
}
input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.15);
  outline: none;
}
/* 去掉某些浏览器可能出现的黑色内边线/高对比模式线条 */
input::-moz-focus-inner {
  border: 0;
}
/* 处理自动填充导致的暗色边框/背景 */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus {
  -webkit-box-shadow: 0 0 0px 1000px #fff inset;
  box-shadow: 0 0 0px 1000px #fff inset;
  -webkit-text-fill-color: #333;
}

.gender-buttons,
.marital-buttons {
  display: flex;
}

.gender-buttons button,
.marital-buttons button {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
  background-color: white;
  cursor: pointer;
}

.gender-buttons button.active,
.marital-buttons button.active {
  background-color: #e0e0e0;
}

.unit {
  margin-left: 5px;
  color: #666;
}
.gender-select-container {
  display: flex;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  padding: 2px;
}

.gender-option {
  flex: 1;
  text-align: center;
  padding: 4px 0;
  cursor: pointer;
  color: #0c0c0c;
  background: #f5f5f5;
}

.gender-option.active {
  background: #ffffff;
  color: var(--el-color-primary);
}
.input__prefix {
  position: absolute;
  right: 26px;
  top: 34px;
}
.blood-pressure-input-container {
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 5px;
  background: #ffffff;
}

.pressure-input {
  flex: 1;
  border: none;
  outline: none;
  padding: 0 8px;
}

.separator {
  margin: 0 8px;
  color: #666;
}

.unit {
  color: #666;
}

.history-form {
  position: relative;
  .table-container {
    width: 100%;
    background: #f5fefd;
    border: 1px solid #dcdcdc;
    border-radius: 4px;
  }

  .table-row {
    display: flex;
    flex-direction: row;
    border-bottom: 1px solid #b3cfe4;

    &:last-child {
      border-bottom: none;
    }
  }

  .table-cell {
    height: 40px;
    display: flex;
    align-items: center;

    &.label-cell {
      width: 12%;
      padding: 0 20px;
      text-align: center;
      border-right: 1px solid #b3cfe4;
    }

    &.input-cell {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-right: 20px;

      input[type='text'] {
        flex: 1;
        border: none;
        background-color: transparent;
        padding: 5px;
      }

      .checkbox-container {
        display: flex;
        align-items: center;

        input[type='checkbox'] {
          margin-left: 10px;
        }
      }
    }
  }
}
::v-deep(.modal-footer) {
  border: none;
}
</style>
<style lang="scss">
.form-item {
  .el-input__prefix {
    display: none;
    position: relative;
  }
  .el-input__suffix-inner {
    color: #666;
  }
}
</style>
